package divinity.utils.web.loaders
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import divinity.utils.web.types.Types;
	
	public class DataLoader extends EventDispatcher
	{
		private var _loaded:Boolean=false;
		private var _target:String;
		private var _destination:Object;
		private var _loader:URLLoader;
		private var _type:String;
		public function DataLoader()
		{
			super();
		}
		public function loadFile(url:String,destination:Object,target:String,type:String=Types.DATA)
		{
			//trace("LOADING CONFIG FILE", url);
			_type=type;
			_target=target;
			_destination=destination;
			var req:URLRequest=new URLRequest(url)
			_loader=new URLLoader();
			_loader.addEventListener(Event.COMPLETE,handle_event);
			_loader.load(req);
			
		}
		private function handle_event(e:Event)
		{
			switch(e.type)
			{
				case Event.COMPLETE:
					configLoaded(e);
					break;				
				default:
					dispatchEvent(e);
					break;				
			}
		}
		protected function configLoaded(e:Event)
		{
			
			_loader.removeEventListener(Event.COMPLETE,configLoaded);	
			if(_type==Types.DATA_JSON)
			{
				//_destination[_target]=JSON.decode(e.target.data);
			}
			if(_type==Types.DATA_XML)
			{
				_destination[_target]=XML(e.target.data);;
			}
			if(_type==Types.DATA)
			{
				_destination[_target]=e.target.data;
				
			}
			_loaded=true;
			dispatchEvent(new Event(Event.COMPLETE))
			_loader=null;
			
		}

		public function get loaded():Boolean
		{
			return _loaded;
		}

		/*public function set loaded(value:Boolean):void
		{
			_loaded = value;
		}
		*/
	}
}